package db.queries;

import java.sql.SQLException;

import core.exceptions.DBAccessException;
import core.objects.User;
import core.objects.UserComment;
import db.dbTables.AbstractDBTable;
import db.dbTables.DbColumn;
import db.dbTables.UserCommentTable;
import db.dbTables.UserTable;
import db.queries.core.ObjectQueries;
import db.queries.core.QueriesEnvironment;

public class UserCommentQueries extends ObjectQueries<UserComment> {

	private static final int QUERY_TYPE_REGULAR = 0;
	private static final int QUERY_TYPE_COMMENTER = 1;
	private static final int QUERY_TYPE_RATING = 2;
	
	private int queryType = QUERY_TYPE_REGULAR;
	
	@Override
	protected AbstractDBTable getTable() {
		return QueriesEnvironment.getUserCommentTable();
	}

	@Override
	protected DBAccessException handleSQLException(SQLException e) {
		if (e.getMessage() != null) {
			String message = e.getMessage();
			if (message.startsWith("Data truncated for column")
					&& message.contains(UserCommentTable.COLUMN_RATING)) {
				return new DBAccessException("Illegal comment: missing rating", e);
			}
		}
		return super.handleSQLException(e);
	}

	@Override
	protected DBAccessException foreignKeyConstrainstViolation(String key,
			Throwable e) {
		if (key.equals(UserTable.COLUMN_ID)) {
			return new DBAccessException("Error: unknown user", e);
		} else if (key.equals(UserCommentTable.COLUMN_COMMENTER_ID)) {
			return new DBAccessException("Error: unknown commenter", e);
		} else if (key.equals(UserCommentTable.COLUMN_COMMENTED_ID)) {
			return new DBAccessException("Error: cannot comment on this user - unknown user", e);
		} else {
			return new DBAccessException("Unknown error has occured", e);
		}
	}
	
	@Override
	protected String orderBy() {
		return " ORDER BY " + QueriesEnvironment.getUserCommentTable().timestamp.getName() + " DESC ";
	}

	@Override
	protected DbColumn getIDColumn() {
		if (queryType == QUERY_TYPE_COMMENTER) {
			return QueriesEnvironment.getUserCommentTable().commenterId;
		} else if (queryType == QUERY_TYPE_RATING) {
			return QueriesEnvironment.getUserCommentTable().rating;
		}
		return QueriesEnvironment.getUserCommentTable().commentedId;
	}

	@Override
	protected void determineField(Object obj) {
		if (obj instanceof Float) {
			queryType = QUERY_TYPE_RATING;
		} else if (obj instanceof User) {
			queryType = QUERY_TYPE_COMMENTER;
		} else {
			queryType = QUERY_TYPE_REGULAR;
		}
	}

	@Override
	protected DbColumn getActualIDColumn() {
		return QueriesEnvironment.getUserCommentTable().commentedId;
	}

	
}
